#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import sys

# 读取两个文件（相对于项目根目录）
with open('../output/SMS_3_output_chunjinggang.json', 'r', encoding='utf-8') as f:
    chujinggang = json.load(f)

with open('../output/SMS_3_output.json', 'r', encoding='utf-8') as f:
    sms3 = json.load(f)

runoffSim_cjg = chujinggang['runoffSim']
rSim_cjg = chujinggang['rSim']  # [RS, RI, RG, ...] 每个是一个数组
timeSeries_sms3 = sms3['timeSeries']

print("=" * 120)
print("SMS_3 模型输出对比")
print("=" * 120)
print(f"初境港输出时段数: {len(runoffSim_cjg)}")
print(f"SMS_3 输出时段数: {len(timeSeries_sms3)}")
print()

# 对比 RunoffSim
print("=" * 120)
print("RunoffSim (总径流) 时间序列对比 (前30个时段)")
print("=" * 120)
print(f"{'索引':<6} {'时间':<20} {'RunoffSim(初境港)':<20} {'RunoffSim(SMS_3)':<20} {'差值':<15} {'一致性':<10}")
print("-" * 120)

runoff_match_count = 0
runoff_total = min(30, len(runoffSim_cjg), len(timeSeries_sms3))

for i in range(runoff_total):
    rs_cjg = runoffSim_cjg[i]
    rs_sms3 = timeSeries_sms3[i]['RunoffSim']
    time_sms3 = timeSeries_sms3[i]['time']
    is_warmup = timeSeries_sms3[i].get('isWarmUp', False)
    
    diff = abs(rs_cjg - rs_sms3)
    is_match = diff < 1e-6
    
    if is_match:
        runoff_match_count += 1
    
    warmup_mark = " [WarmUp]" if is_warmup else ""
    match_mark = "✓" if is_match else "✗"
    
    print(f"{i:<6} {time_sms3:<20} {rs_cjg:<20.6f} {rs_sms3:<20.6f} {diff:<15.9f} {match_mark:<10}{warmup_mark}")

print(f"\nRunoffSim 一致性: {runoff_match_count}/{runoff_total} ({runoff_match_count*100/runoff_total:.1f}%)")

# 对比 RS (地表径流)
print("\n" + "=" * 120)
print("RS (地表径流) 时间序列对比 (前30个时段)")
print("=" * 120)
print(f"{'索引':<6} {'时间':<20} {'RS(初境港)':<20} {'RS(SMS_3)':<20} {'差值':<15} {'一致性':<10}")
print("-" * 120)

rs_match_count = 0
rs_total = min(30, len(rSim_cjg[0]), len(timeSeries_sms3))

for i in range(rs_total):
    rs_cjg = rSim_cjg[0][i]  # RS 是 rSim 的第一个数组
    rs_sms3 = timeSeries_sms3[i]['RS']
    time_sms3 = timeSeries_sms3[i]['time']
    is_warmup = timeSeries_sms3[i].get('isWarmUp', False)
    
    diff = abs(rs_cjg - rs_sms3)
    is_match = diff < 1e-6
    
    if is_match:
        rs_match_count += 1
    
    warmup_mark = " [WarmUp]" if is_warmup else ""
    match_mark = "✓" if is_match else "✗"
    
    print(f"{i:<6} {time_sms3:<20} {rs_cjg:<20.6f} {rs_sms3:<20.6f} {diff:<15.9f} {match_mark:<10}{warmup_mark}")

print(f"\nRS 一致性: {rs_match_count}/{rs_total} ({rs_match_count*100/rs_total:.1f}%)")

# 对比 RI (壤中流)
print("\n" + "=" * 120)
print("RI (壤中流) 时间序列对比 (前30个时段)")
print("=" * 120)
print(f"{'索引':<6} {'时间':<20} {'RI(初境港)':<20} {'RI(SMS_3)':<20} {'差值':<15} {'一致性':<10}")
print("-" * 120)

ri_match_count = 0
ri_total = min(30, len(rSim_cjg[1]), len(timeSeries_sms3))

for i in range(ri_total):
    ri_cjg = rSim_cjg[1][i]  # RI 是 rSim 的第二个数组
    ri_sms3 = timeSeries_sms3[i]['RI']
    time_sms3 = timeSeries_sms3[i]['time']
    is_warmup = timeSeries_sms3[i].get('isWarmUp', False)
    
    diff = abs(ri_cjg - ri_sms3)
    is_match = diff < 1e-6
    
    if is_match:
        ri_match_count += 1
    
    warmup_mark = " [WarmUp]" if is_warmup else ""
    match_mark = "✓" if is_match else "✗"
    
    print(f"{i:<6} {time_sms3:<20} {ri_cjg:<20.6f} {ri_sms3:<20.6f} {diff:<15.9f} {match_mark:<10}{warmup_mark}")

print(f"\nRI 一致性: {ri_match_count}/{ri_total} ({ri_match_count*100/ri_total:.1f}%)")

# 对比 RG (地下径流)
print("\n" + "=" * 120)
print("RG (地下径流) 时间序列对比 (前30个时段)")
print("=" * 120)
print(f"{'索引':<6} {'时间':<20} {'RG(初境港)':<20} {'RG(SMS_3)':<20} {'差值':<15} {'一致性':<10}")
print("-" * 120)

rg_match_count = 0
rg_total = min(30, len(rSim_cjg[2]), len(timeSeries_sms3))

for i in range(rg_total):
    rg_cjg = rSim_cjg[2][i]  # RG 是 rSim 的第三个数组
    rg_sms3 = timeSeries_sms3[i]['RG']
    time_sms3 = timeSeries_sms3[i]['time']
    is_warmup = timeSeries_sms3[i].get('isWarmUp', False)
    
    diff = abs(rg_cjg - rg_sms3)
    is_match = diff < 1e-6
    
    if is_match:
        rg_match_count += 1
    
    warmup_mark = " [WarmUp]" if is_warmup else ""
    match_mark = "✓" if is_match else "✗"
    
    print(f"{i:<6} {time_sms3:<20} {rg_cjg:<20.6f} {rg_sms3:<20.6f} {diff:<15.9f} {match_mark:<10}{warmup_mark}")

print(f"\nRG 一致性: {rg_match_count}/{rg_total} ({rg_match_count*100/rg_total:.1f}%)")

# 全部时段统计
print("\n" + "=" * 120)
print("全部时段统计")
print("=" * 120)

total_len = min(len(runoffSim_cjg), len(timeSeries_sms3))
runoff_all_match = sum(1 for i in range(total_len) if abs(runoffSim_cjg[i] - timeSeries_sms3[i]['RunoffSim']) < 1e-6)
rs_all_match = sum(1 for i in range(total_len) if abs(rSim_cjg[0][i] - timeSeries_sms3[i]['RS']) < 1e-6)
ri_all_match = sum(1 for i in range(total_len) if abs(rSim_cjg[1][i] - timeSeries_sms3[i]['RI']) < 1e-6)
rg_all_match = sum(1 for i in range(total_len) if abs(rSim_cjg[2][i] - timeSeries_sms3[i]['RG']) < 1e-6)

print(f"总时段数: {total_len}")
print(f"RunoffSim 完全一致的时段数: {runoff_all_match}/{total_len} ({runoff_all_match*100/total_len:.1f}%)")
print(f"RS (地表径流) 完全一致的时段数: {rs_all_match}/{total_len} ({rs_all_match*100/total_len:.1f}%)")
print(f"RI (壤中流) 完全一致的时段数: {ri_all_match}/{total_len} ({ri_all_match*100/total_len:.1f}%)")
print(f"RG (地下径流) 完全一致的时段数: {rg_all_match}/{total_len} ({rg_all_match*100/total_len:.1f}%)")

# 最终状态对比
print("\n" + "=" * 120)
print("最终状态对比")
print("=" * 120)

# 获取初境港的最终状态（数组的最后一个或倒数第二个值）
wup_cjg = float(chujinggang['newStatus']['WUP'][-1])
wlp_cjg = float(chujinggang['newStatus']['WLP'][-1])
wdp_cjg = float(chujinggang['newStatus']['WDP'][-1])
sp_cjg = float(chujinggang['newStatus']['SP'][-1])
frp_cjg = float(chujinggang['newStatus']['FRP'][-1])

# 获取 SMS_3 的最终状态
wup_sms3 = sms3['finalState']['WUP']
wlp_sms3 = sms3['finalState']['WLP']
wdp_sms3 = sms3['finalState']['WDP']
sp_sms3 = sms3['finalState']['SP']
frp_sms3 = sms3['finalState']['FRP']

wup_match = abs(wup_cjg - wup_sms3) < 1e-6
wlp_match = abs(wlp_cjg - wlp_sms3) < 1e-6
wdp_match = abs(wdp_cjg - wdp_sms3) < 1e-6
sp_match = abs(sp_cjg - sp_sms3) < 1e-6
frp_match = abs(frp_cjg - frp_sms3) < 1e-6

print(f"WUP (上层张力水): 初境港={wup_cjg:.10f}, SMS_3={wup_sms3:.10f}, 差值={abs(wup_cjg - wup_sms3):.10f} {'✓' if wup_match else '✗'}")
print(f"WLP (下层张力水): 初境港={wlp_cjg:.10f}, SMS_3={wlp_sms3:.10f}, 差值={abs(wlp_cjg - wlp_sms3):.10f} {'✓' if wlp_match else '✗'}")
print(f"WDP (深层张力水): 初境港={wdp_cjg:.10f}, SMS_3={wdp_sms3:.10f}, 差值={abs(wdp_cjg - wdp_sms3):.10f} {'✓' if wdp_match else '✗'}")
print(f"SP (自由水深): 初境港={sp_cjg:.10f}, SMS_3={sp_sms3:.10f}, 差值={abs(sp_cjg - sp_sms3):.10f} {'✓' if sp_match else '✗'}")
print(f"FRP (产流面积系数): 初境港={frp_cjg:.10f}, SMS_3={frp_sms3:.10f}, 差值={abs(frp_cjg - frp_sms3):.10f} {'✓' if frp_match else '✗'}")

# 总体结论
print("\n" + "=" * 120)
print("总体结论")
print("=" * 120)

if (runoff_all_match == total_len and rs_all_match == total_len and 
    ri_all_match == total_len and rg_all_match == total_len and
    wup_match and wlp_match and wdp_match and sp_match and frp_match):
    print("✓✓✓ 两个模型输出**完全一致**！")
    sys.exit(0)
elif (runoff_all_match >= total_len * 0.95 and rs_all_match >= total_len * 0.95 and
      ri_all_match >= total_len * 0.95 and rg_all_match >= total_len * 0.95):
    print("⚠ 两个模型输出基本一致，但存在少量差异")
    sys.exit(0)
else:
    print("✗✗✗ 两个模型输出存在显著差异，需要进一步检查")
    
    # 找出第一个不匹配的时段
    first_diff_runoff = next((i for i in range(total_len) if abs(runoffSim_cjg[i] - timeSeries_sms3[i]['RunoffSim']) >= 1e-6), -1)
    first_diff_rs = next((i for i in range(total_len) if abs(rSim_cjg[0][i] - timeSeries_sms3[i]['RS']) >= 1e-6), -1)
    first_diff_ri = next((i for i in range(total_len) if abs(rSim_cjg[1][i] - timeSeries_sms3[i]['RI']) >= 1e-6), -1)
    first_diff_rg = next((i for i in range(total_len) if abs(rSim_cjg[2][i] - timeSeries_sms3[i]['RG']) >= 1e-6), -1)
    
    if first_diff_runoff >= 0:
        print(f"\n第一个 RunoffSim 不匹配出现在索引 {first_diff_runoff}")
        print(f"  时间: {timeSeries_sms3[first_diff_runoff]['time']}")
        print(f"  初境港: {runoffSim_cjg[first_diff_runoff]:.10f}")
        print(f"  SMS_3:  {timeSeries_sms3[first_diff_runoff]['RunoffSim']:.10f}")
        print(f"  差值:   {abs(runoffSim_cjg[first_diff_runoff] - timeSeries_sms3[first_diff_runoff]['RunoffSim']):.10f}")
    
    if first_diff_rs >= 0:
        print(f"\n第一个 RS 不匹配出现在索引 {first_diff_rs}")
        print(f"  时间: {timeSeries_sms3[first_diff_rs]['time']}")
        print(f"  初境港: {rSim_cjg[0][first_diff_rs]:.10f}")
        print(f"  SMS_3:  {timeSeries_sms3[first_diff_rs]['RS']:.10f}")
        print(f"  差值:   {abs(rSim_cjg[0][first_diff_rs] - timeSeries_sms3[first_diff_rs]['RS']):.10f}")
    
    if first_diff_ri >= 0:
        print(f"\n第一个 RI 不匹配出现在索引 {first_diff_ri}")
        print(f"  时间: {timeSeries_sms3[first_diff_ri]['time']}")
        print(f"  初境港: {rSim_cjg[1][first_diff_ri]:.10f}")
        print(f"  SMS_3:  {timeSeries_sms3[first_diff_ri]['RI']:.10f}")
        print(f"  差值:   {abs(rSim_cjg[1][first_diff_ri] - timeSeries_sms3[first_diff_ri]['RI']):.10f}")
    
    if first_diff_rg >= 0:
        print(f"\n第一个 RG 不匹配出现在索引 {first_diff_rg}")
        print(f"  时间: {timeSeries_sms3[first_diff_rg]['time']}")
        print(f"  初境港: {rSim_cjg[2][first_diff_rg]:.10f}")
        print(f"  SMS_3:  {timeSeries_sms3[first_diff_rg]['RG']:.10f}")
        print(f"  差值:   {abs(rSim_cjg[2][first_diff_rg] - timeSeries_sms3[first_diff_rg]['RG']):.10f}")
    
    sys.exit(1)

